import { AwakeSystem } from "../../../../../Core/Module/EventSystem/IAwakeSystem";
import { DestroySystem } from "../../../../../Core/Module/EventSystem/IDestroySystem";
import { ExpandOf, FriendOf, ObjectSystemAttribute } from "../../../../../Decorator/Decorator";
import { LocalStorageHelper } from "../../../../HotfixView/Client/Module/LocalStorage/LocalStorageHelper";
import { LocalStorageComponent } from "../../../../ModelView/Client/Module/LocalStorage/LocalStorageComponent";

/**
 * 使用 Expand 扩展方法
 * 
 * 必须作出以下申明，才能调用对象的扩展方法
 */
declare module "../../../../ModelView/Client/Module/LocalStorage/LocalStorageComponent" {

    interface LocalStorageComponent {
        SetItem<T>(key: string, value: T): void;
        GetItem<T>(key: string, defaultValue: T): T;
        RemoveItem(key: string): void;
    }

}

@ExpandOf(LocalStorageComponent)
export class LocalStorageComponentSystem {

    private static SetItem<T>(self: LocalStorageComponent, key: string, value: T): void {
        LocalStorageHelper.SetItem(key, value.toString());
    }

    private static GetItem<T>(self: LocalStorageComponent, key: string, defaultValue: T): T {
        let value = LocalStorageHelper.GetItem(key);
        if (!value) {
            return defaultValue;
        }
        if (typeof defaultValue === "number") {
            return parseInt(value) as T;
        }
        return value as T;
    }

    private static RemoveItem(self: LocalStorageComponent, key: string): void {
        LocalStorageHelper.RemoveItem(key);
    }

}

@FriendOf(LocalStorageComponent)
@ObjectSystemAttribute()
export class LocalStorageComponentAwakeSystem extends AwakeSystem<LocalStorageComponent> {

    Awake(self: LocalStorageComponent): void {
        LocalStorageComponent.Instance = self;
    }

}

@FriendOf(LocalStorageComponent)
@ObjectSystemAttribute()
export class LocalStorageComponentDestroySystem extends DestroySystem<LocalStorageComponent> {

    Destroy(self: LocalStorageComponent): void {
        LocalStorageComponent.Instance = null;
    }

}